package org.mf.security.service.impl;

import org.mf.dao.UserDAO;
import org.mf.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.google.inject.persist.Transactional;

@Service("jpaUserDetailsService")
@Transactional
public class JpaUserDetailsService implements UserDetailsService {

	private UserDAO userDao;

	@Autowired
	public JpaUserDetailsService(UserDAO userDao) {
		this.userDao = userDao;
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		// declare a null spring user
		UserDetails springUser = null;

		try {
			User user = userDao.getUserByUsername(username);
			System.out.println("authorities:" + user.getAuthorities());
			springUser = new org.springframework.security.core.userdetails.User(
					user.getUsername(), user.getPassword(), true, true, true,
					true, user.getGrantedAuthorities());
		} catch (Exception e) {
			throw new UsernameNotFoundException("Error in retrieving user");
		}

		return springUser;
	}

}
